<?php
/**
 * File Name...: libraries\router.php
 * Framework...: Blackbird Framework
 * Author......: KnKill, 2010 (c) KnKill Corporation
 */



class Router
{


/**
 * @access private
 * @var string Путь к контролёрам
 * @since 0.1
 */
private $path;


/**
 * @access private
 * @var array Аргументы функции
 * @since 0.1
*/
private $arguments = array();


/**
 * @access public
 * @since 0.1
 * @param string $path Путь к контролёрам
 * @return bool
 */
public function set_path($path) {
    $path = trim($path, '\\') . DS;
    if (! is_dir($path)) {
        throw new Exception ('Неверный путь к контролёрам: `' . $path . '`');
        return false;
    }
    $this->path = $path;
    return $this;
}


/**
 * @access public
 * @since 0.1
 * @return mixed Результат функции
 */
public function go() {
    $this->get_controller($file, $controller, $action, $arguments);
    if (! is_readable($file)) {
        // TODO: 404 HERE
        return false;
    }
    include $file;
    $class = 'Controller_' . $controller;
    $controller = new $class();
    if (is_callable(array($controller, $action)) == false) {
        // TODO: 404 HERE
        return false;
    }
    // Гоп-стоп
    if (substr($action, 0, 2) == '__' && substr($action, 2, 1) != '_') {
        // TODO: 403 HERE
        return false;
    }
    return call_user_func_array(array($controller, $action), $arguments);
}


/**
 * @access private
 * @since 0.1
 * @param string &$file
 * @param string &$controller
 * @param string &$action
 * @param string &arguments
 */
private function get_controller(&$file, &$controller, &$action, &$arguments) {
    // Парсим URL, в частности параметр route и делим полученную строку на
    // части.
    $route = empty($_GET['route']) ? 'index' : $_GET['route'];
    $parts = explode('/', trim($route, '/\\'));
    $cmd_path = $this->path;
    foreach ($parts as $part) {
        $fullpath = $cmd_path . $part;
        if (is_dir($fullpath)) {
            $cmd_path .= $part . DS;
            array_shift($parts);
            continue;
        }
        if (is_file($fullpath . '.php')) {
            $controller = $part;
            array_shift($parts);
            break;
        }
    }
    if (empty($controller)) {
        $controller = 'index';
    }
    $action = array_shift($parts);
    if (empty($action)) {
        $action = 'index';
    }
    $file = $cmd_path . $controller . '.php';
    $arguments = $parts;
}


// End Of Class "Router"
}